import { useEffect, useState } from "react";
import { StaffList, Staffdel, Stafftype, Staffadd, Staffdelall } from "../apis/clerk/index";
import { buildinglist } from '../apis/house/index'
import "../assets/scss/staffs/staffs.scss";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import {
  Space, Table, Button, Form, Input, Select, Pagination, Modal, Radio, message, Cascader, Upload, Tooltip, Popconfirm
} from "antd";
const Staff = (): JSX.Element => {
  const [list, setList] = useState([])
  const paramsType = { page: 1, psize: 10 }
  const [typeList, setTypeList] = useState([])
  const [total, setTotal] = useState()
  const [title, setTitle] = useState({ title: "添加职员" })
  const [params, setParams] = useState({ key: "", page: 1, psize: 10, type: 1 });
  // 列表
  const getData = async () => {
    const res: any = await StaffList(params);
    if (res && res.errCode === 10000) {
      setList(res.data.list);
      setTotal(res.data.counts)
      console.log(3333333333, res);

    }
  }
  // 类型列表
  const getTypeLists = async () => {
    const res: any = await Stafftype(paramsType);
    if (res && res.errCode === 10000) {
      setTypeList(res.data.list);
    }
  }
  // 表格数据
  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '职员类型',
      dataIndex: 'type',
      key: 'type',
      render: (text: any) => {
        if (text === 1) {
          return (
            text = "项目经理"
          )
        } else if (text === 2) {
          return (
            text = "财务总监"
          )
        } else if (text === 3) {
          return (
            text = "普通职员"
          )
        }
      }
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (text: any) => {
        if (text === 0) {
          return (
            text = "女"
          )
        } if (text === 1) {
          return (
            text = '男'
          )
        }
      }
    },
    {
      title: '身份证号',
      dataIndex: 'cardid',
      key: 'cardid',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '管理小区',
      dataIndex: 'building',
      key: 'building',
      render: (text: any, list: any) => {
        console.log(text);

        if (!list.building.length) {
          return <div>暂无数据</div>
        } else if (list.building.length === 1) {
          return <div>{list.building[0].building}</div>
        } else {
          return (
            <Tooltip title={list.building.map((e: any) => (
              <div>{e.building}</div>
            ))} trigger="click" defaultOpen>
              <div>{list.building[0].building}</div>
            </Tooltip>
          )
        }
      },
    },
    {
      title: '操作',
      key: '操作',
      render: (record: any) => (
        <Space size="middle">
          <Button onClick={() => editClick(record)} style={{ color: "#fff", backgroundColor: "#67c23a", borderRadius: '5px', border: 'none' }}>修改</Button>
          {/* <Button type="primary" danger onClick={() => deleteClick(record.id)} style={{ color: "#fff", borderRadius: '5px', border: 'none' }}>删除</Button> */}
          <Popconfirm
            placement="topRight"
            title="确认删除?"
            onConfirm={confirm(record.id)}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          >
            <Button type="primary" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    }
  ];
  // 全选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 删除确认框
  const confirm = (id: any) => {
    return () => {
      // console.log(id);
      deleteClick(id);
    }
  };
  // 批删确认框
  const delAllConfirm = () => {
    // return () => {
    console.log(selectedRowKeys);
    delall();
    // }
  };

  //删除
  const deleteClick = async (id: number) => {
    console.log(id);
    const res: any = await Staffdel({ id: id })
    console.log(res);
    if (res.errCode === 10000) {
      message.success("删除成功")
      getData()
    } else {
      message.error("删除失败")

    }
  }
  //批量删除
  const delall = async () => {
    const res = await Staffdelall({ ids: selectedRowKeys })
    console.log('批量删除', res);
    getData()
  }
  // 搜索
  const onFinish = (values: any) => {
    console.log(values);
    setParams({ ...params, ...values, page: 1 })
  }
  // 分页
  const changePage = (page: number, psize: number) => {
    setParams({ ...params, page, psize })
  }
  // 对话框
  const [open, setOpen] = useState(false);
  const [addStaff, setAddStaff] = useState<any>({ id: 0, buildingid: 0, photo: '', name: "", type: "", sex: "", cardid: "", mobile: "" })
  // 点击添加
  const showModal = () => {
    setOpen(true);
  };
  //数据回显
  const [form] = Form.useForm();
  // 修改
  const editClick = (row: any) => {
    setTitle({ title: "修改职员" })
    setOpen(true);
    setAddStaff({ ...addStaff, id: row.id })
    form.setFieldsValue({ name: row.name, type: row.type, sex: row.sex, cardid: row.cardid, mobile: row.mobile })
  }
  // 点击对话框确认
  const handleOk = (val: any) => {
    console.log(val);
    val.photo = val.photo.file.response.data
    val.pass = null
    setTimeout(async () => {
      setOpen(false);
      const res: any = await Staffadd({ ...val, building: [{ buildingid: addStaff.buildingid }], id: addStaff.id })
      if (res.errCode === 10000) {
        let mmmm: any = !addStaff.id ? "添加成功" : '修改成功'
        message.success(mmmm)
        getData()
        //添加完成让他成为空对象
        setAddStaff({})
      }
    }, 1000);
  };
  //取消
  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };
  // 上传图片
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    // console.log(info.file,555);

    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        // console.log(url,999);

        setLoading(false);
        setImageUrl(url);
      });
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  let token = sessionStorage.getItem("token")
  const props: any = {
    name: "file",
    listType: "picture-card",
    action: "http://estate.eshareedu.cn/estate/api/upload/add",
    headers: {
      "Authorization": token
    },
    beforeUpload: beforeUpload,
    onChange: handleChange
  };
  // 级联选择器
  //楼栋列表
  const [building, useBuilding] = useState([])
  const getBuilding = async () => {
    const res: any = await buildinglist()
    console.log('楼栋列表', res)
    if (res && res.errCode == 10000) {
      useBuilding(res.data.list)
    }
  }

  const cancel = () => {
    // console.log(e);
    message.error('已取消');
  };

  //查看 并调用房间列表
  const onChange = (val: any) => {
    console.log(val);
  }
  // 挂载
  useEffect(() => {
    getData()
    getTypeLists()
    getBuilding()
  }, [params])
  return (
    <div className='staff'>
      <div className="staff-hd">
        <p className='span'>职员列表</p>
      </div>

      <div className='xian' ></div>
      {/* 查询 */}
      <Form
        className='staff-form'
        layout="horizontal"
        onFinish={onFinish}
        form={form}
      >
        <Form.Item label="姓名" name='key'>
          <Input className='form-inpt' placeholder="职员名" />
        </Form.Item>

        <Form.Item className="type" label="职员类型" name='type'>
          <Select className='form-type' placeholder="请选择">
            {typeList.map((item: any) => {
              return (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              )
            })}
          </Select>
        </Form.Item>

        <Form.Item>
          <Button type="primary" className="form_btn" htmlType="submit">查询</Button>
        </Form.Item>

      </Form>
      {/* 添加 删除按钮 */}
      <div style={{ marginBottom: '20px' }}>
        <Space size='middle'>
          <Button type="primary" onClick={showModal}>
            添加
          </Button>
          {/* <Button type="primary" danger onClick={delall}>
          批量删除
        </Button> */}
          <Popconfirm
            placement="topRight"
            title="确认全部删除?"
            onConfirm={delAllConfirm}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          >
            <Button type="primary" danger size='large' className="delall">批量删除</Button>
          </Popconfirm>
        </Space>
      </div>
      {/* 表格 */}
      <Table
        columns={columns}
        dataSource={list}
        pagination={false}
        bordered
        rowKey={(columns) => columns.id}
        rowSelection={rowSelection}
        style={{ marginTop: '30px' }}
      />
      {/* 分页 */}
      <Pagination
        total={total}
        className="pagination"
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 页`}
        onChange={changePage}
      />
      {/* 添加对话框 */}
      <Modal
        className='staff-modal'
        title={title.title}
        open={open}
        width={700}
        onCancel={handleCancel}
        footer={[]}
      >
        <Form
          layout="horizontal"
          className='staff-add'
          onFinish={handleOk}
          style={{ display: "flex" }}
          form={form}
        >
          <div className='staff-left' style={{ flex: 1 }}>
            <Form.Item label="照片" name="photo" rules={[{ required: true, message: '请上传图片' }]}>
              <Upload {...props}>
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
              </Upload>
            </Form.Item>
            <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
              <Input className='staff-ipt' style={{ width: "200px", marginLeft: "38px" }} />
            </Form.Item>
            <Form.Item label="管辖范围" name="building">
              <Cascader style={{ width: '200px', marginLeft: '20px' }} onChange={onChange} options={building}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }} placeholder="请选择" />
            </Form.Item>
            <Form.Item label="职员类型" name="type" rules={[{ required: true, message: '请选择职员类型' }]}>
              <Select style={{ width: "200px", marginLeft: "10px" }}>
                {typeList.map((item: any) => {
                  return (
                    <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                  )
                })}
              </Select>
            </Form.Item>
            <Form.Item label="性别" name="sex">
              <Radio.Group name="radiogroup" defaultValue={1} style={{ marginLeft: "40px" }}>
                <Radio value={1}>男</Radio>
                <Radio value={0}>女</Radio>
              </Radio.Group>
            </Form.Item>
          </div>
          <div className='staff-right' style={{ flex: 1 }}>
            <Form.Item label="身份证号" name="cardid" rules={[{ required: true, message: '请输入身份证号' }]}>
              <Input style={{ width: "200px", marginLeft: "10px" }} />
            </Form.Item>
            <Form.Item label="联系电话" name="mobile" rules={[{ required: true, message: '请输入联系电话' }]}>
              <Input style={{ width: "200px", marginLeft: "10px" }} />
            </Form.Item>
            <div style={{ marginTop: '300px', marginLeft: '100px' }}>
              <Form.Item >
                <Button htmlType="button" style={{ margin: '0 8px' }} onClick={handleCancel}>
                  取消
                </Button>
                <Button htmlType="submit" type="primary">
                  确定
                </Button>
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>
    </div>);
}
export default Staff;